<template>
  <div>

      <el-button type="primary" @click="showAddUser" >添加用户</el-button>
			<el-button type="danger" @click="batchDeleteUser" >删除用户</el-button>
    <!--分页-->
    <el-pagination
      :page-size="page.pageSize"
      :total="page.totalCount"
      :current-page.sync="page.pageNo"
      @current-change="initTableData"
      layout="total, prev, pager, next, jumper">
    </el-pagination>

    <!--表格内容-->
    <el-table
      ref="list"
      :data="tableData"
      style="width: 100%"
      border
      stripe
      highlight-current-row
      @row-click="handleRowClick"
      @select-all="handleCheckedAllAndCheckedNone"
      @select="handleCheckedAllAndCheckedNone"


	  height="400"
	  :row-style="tableRowStyle"
	  :header-cell-style="tableHeaderColor"

	  >

      <el-table-column
        type="selection"
        width="45"
        align="center">
      </el-table-column>

      <el-table-column
        type="index"
        label="序号"
        width="50">
      </el-table-column>
      <el-table-column
        property="username"
        label="用户名"
        width="180">
      </el-table-column>
      <el-table-column
        property="password"
        label="密码">
      </el-table-column>
       <el-table-column
        property="realName"
        label="真实姓名">
      </el-table-column>
      <el-table-column
      :formatter="formatterStatus"
        property="sex"
        label="性别">
      </el-table-column>
      <el-table-column
        property="birthday"
        label="生日">
      </el-table-column>
      <el-table-column
        property="phone"
        label="电话">
      </el-table-column>

      <el-table-column
      property="email"
        label="邮箱">
      </el-table-column>

	<el-table-column  label="用户头像">
	          <template slot-scope="scope">
	              <el-popover placement="top-start" title="" trigger="hover">
	                <img :src="`http://localhost:8082/file/${scope.row.userImages}`" alt="" style="width: 150px;height: 150px">
	                <img slot="reference" :src="`http://localhost:8082/file/${scope.row.userImages}`" style="width: 60px;height: 60px">
	              </el-popover>
	          </template>
	        </el-table-column>

      <el-table-column
        label="操作"
        width="130"
        align="center">
        <template slot-scope="scope">
          <el-button circle icon="el-icon-edit-outline" type="primary" title="编辑" size="small"
            @click="rowEdit(scope.$index, scope.row)"></el-button>
          <el-button circle icon="el-icon-delete" type="danger" title="删除" size="small"
            @click="rowDel(scope.row.id);"></el-button>
        </template>
      </el-table-column>
    </el-table>
    <!--编辑-弹出层-->
    <el-dialog
      :title="dialogName"
      :visible.sync="isShowEditDialog"
      width="830px"
      @close="dialogClose">
      <el-form
        ref="editForm"
        :model="user"
        label-width="55px">

        <el-form-item label="用户名"  prop="username">
           <el-input v-model="user.username"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="user.password"></el-input>
        </el-form-item>
        <el-form-item label="真实姓名" prop="realName">
          <el-input v-model="user.realName"></el-input>
        </el-form-item>

        <el-form-item label="性别" prop="sex">
          <el-input v-model="user.sex"></el-input>
        </el-form-item>

        <el-form-item label="生日" prop="birthday">
          <el-input v-model="user.birthday"></el-input>
        </el-form-item>

        <el-form-item label="手机号码" prop="phone">
          <el-input v-model="user.phone"></el-input>
        </el-form-item>

        <el-form-item label="邮箱" prop="email">
          <el-input v-model="user.email"></el-input>
        </el-form-item>

		<el-form-item label="用户头像">
						 <el-upload
						   action="http://localhost:8082/user/uploadImages"
						   list-type="picture-card"
						   :show-file-list="false"
						   :on-success="getImageUrl"
						   >
						     <el-image v-if="user.userImages"
						         style="width: 110px; height: 110px"
						         :src='user.userImages'
						         fit="cover">
						   </el-image>
						   <i v-else class="el-icon-plus"></i>
						 </el-upload>

		                  </el-form-item>


        <el-form-item>
          <el-button type="primary" @click="handleEdit(user.id)" class="pull-right margin-l-25">确定</el-button>
          <el-button @click="cancelEdit" class="pull-right">取消</el-button>
        </el-form-item>

      </el-form>
    </el-dialog>
  </div>
</template>
setCurRowChecked
<script>
import axios from 'axios';
  export default {
    name: "Table",
    data() {
      return {
        dialogName: '' , //编辑框显示名称
        typeList: [], // 类别集合
        user: {
          id:null,
          username: '',
          password:'',
          realName:'',
          sex:'',
          birthday: '',
          phone: '',
          email: '',
          userImages: ''
        },
        page:{ //分页参数
           pageNo : 1,
           pageSize: 6,
           totalCount: 0
        },
        //商品数据列表
        tableData: [],
        isShowEditDialog: false
      }
    },
    methods: {
      formatterStatus(row, column, cellValue, index){
          var st = '未知' ;
          switch(cellValue){
             case 1:
                st = "男";
                break ;
             case 0:
                st = "女";
                break ;

          }
          return st ;
      },
      //显示添加商品页面
      showAddUser(){
        this.user = {} ;
         this.dialogName = '添加用户'
         this.isShowEditDialog = true;
      },
      handleRowClick(row, event, column) {

        // 仅选中当前行
        this.setCurRowChecked;
      },
      handleCheckedAllAndCheckedNone(selection) {

        // 当前选中仅一行时操作-（当前表格行高亮）
        1 != selection.length && this.$refs.list.setCurrentRow();
      },
      dialogClose() {

        // 清空编辑表单
        this.$refs.editForm.resetFields();
      },
      //显示编辑图书页面
      rowEdit(index, row) {
       this.dialogName = '编辑用户'
       this.user = row
       this.isShowEditDialog = true;
      },
      //取消后，清掉弹出框内容
      cancelEdit(){
        this.user = {}
        this.isShowEditDialog = false;
      },

	  batchDeleteUser(){
	   var sels=this.$refs.list.selection; //获取所有选择的行
	   var ids=[];
	   ids=sels.map(user=>user.id)
	   console.log(ids)

	   this.$confirm('确定要删除当前选中的行吗？', '删除', {
	      comfirmButtonText: '确定',
	      cancelButtonText: '取消'
	    }).then(() => {
	      axios.post('http://localhost:8082/user/batchDeleteUser?ids='+ids)

	           .then(res =>{
	               if(res.data.code == 200){
	                     this.$message.success('删除成功');
	                     this.initTableData();
	               }else{
	                this.$message.success('删除失败!');
	               }
	           })
	      return false;
	    });
	    //console.log("+++++++"+id)
	  },

      handleEdit(id) {
       console.log("编辑获取用户id"+id)
        this.$refs.editForm.validate(isValid => {

          if (!isValid) return;

          // 保存编辑后的数据
         axios.get('http://localhost:8082/user/save',{params:this.user})

              .then(res =>{

                   if(res.data.code == 200){
                    //编辑完成后,去掉编辑弹出框
                     this.isShowEditDialog = false;
                     this.$message.success('保存成功');
                     this.initTableData()
                   }else{
                     this.isShowEditDialog = false;
                     // 考虑到可能编辑了日期-需要重新排序
                     // ***注意：手动排序传参和表格的default-sort属性格式不太一样
                     this.$message.success('保存失败');
                   }
              })

              console.log("编辑获取用户参数"+this.user)

        });
      },

      rowDel(id) {
            console.log("id :  " +id)
        this.$confirm('确定要删除当前行吗？', '删除', {
          comfirmButtonText: '确定',
          cancelButtonText: '取消'
        }).then(() => {
          axios.post('http://localhost:8082/user/deleteUser?id=' +id)
               .then(res =>{
                   if(res.data.code == 200){
                         this.$message.success('删除成功');
                         this.initTableData();
                   }
               })
          return false;
        });
      },




      //初始化table数据
      initTableData(){
        console.log("pageNo :  " + this.page.pageNo)
         axios.get('http://localhost:8082/user/getPage',{params: this.page})
              .then(res =>{
                   if(res.data.code == 200){
                      this.page.totalCount = res.data.data.total
                      this.tableData = res.data.data.list
					   console.log("page.totalCount" +  this.page.totalCount)
					   console.log("this.tableData"+  this.tableData)
                   }
              })
      },

	 initTypeData(){
	    axios.get('http://localhost:8082/user/getTypePage')
	         .then(res => {
	             this.typeList = res.data.data
	         })
	  },


	    //上传成功之后的回调函数
		  getImageUrl(res,file){
			  //返回的是图片上传的图片名
			  this.user.userImages = res ;
		  },

		  tableRowStyle({ row, rowIndex }) {
		        return 'background-color: #F7F6Fd;'
		        },
		        // 修改table header的背景色
		  tableHeaderColor({ row, column, rowIndex, columnIndex }) {
		        if (rowIndex === 0) {
		          return 'background-color: lightblue;color: #303133;font-weight: 500;font-size: 20px;' //font-size: 20px;为字体大小设置
		        }
		        },

    },
    mounted(){
       this.initTableData()
	   this.initTypeData()

    }

    }

</script>

<style scoped lang="less">
.el-form {
  padding: 0 10px;
}
.el-date-editor {
  width: 100% !important;
}
</style>
